package com.ceba.test.modules.email.logicService;

import java.util.*;

import javax.mail.AuthenticationFailedException;
import javax.mail.internet.MimeUtility;

import abc.net.mail.client.MailClient;
import abc.util.FileHelper;
import abc.util.StringUtils;
import com.ceba.base.helper.LoggerHelper;
import com.ceba.cebautils.StringUtil;
import com.ceba.test.base.config.LogicPathUtil;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.modules.email.entity.*;
import com.ceba.test.modules.storage.logicService.StorageFileCacheManage;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidubce.services.ses.model.SendEmailRequest.Mail;
import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.base.web.UserUtils;
import com.ceba.test.modules.email.service.MsgEmailSetService;
import com.ceba.test.modules.email.service.MsgEmailValidLogService;
import com.ceba.test.modules.email.service.MsgMailService;
import com.ceba.test.modules.filemanage.dto.VFileObject;

import abc.IContextDictionary;
import abc.user.IUser;
import abc.web.HttpContext;

public class EmailLogicService {

	private static Logger logger = LoggerFactory.getLogger(EmailLogicService.class);


	private MsgEmailSetService msgEmailSetService;
	private MsgMailService msgMailService;
	private MsgEmailValidLogService msgEmailValidLogService;

	public MsgEmailSet getMsgEmailSetById(String id) {
		return msgEmailSetService.getMsgEmailSetById(id);
	}

	/**
	 * 获取所有
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getDataTable(String type) throws Exception {
		return msgEmailSetService.getDataTable(type).toJSON();
	}

	/**
	 * 修改
	 * 
	 * @return
	 */
	public boolean modify(MsgEmailSet msgEmail) {
		return msgEmailSetService.modify(msgEmail);
	}


	/*
	 * 获取发送邮件列表
	 */
	public List<MsgMailSend> getSendEMail() {
		return msgEmailSetService.getSendEMail();
	}

	

	// MsgMailService类

	public Boolean sendEmail(String title, String mailBody, String path, String mailTo, String reportName,
			String loginUserId) {
		return msgMailService.sendEmail(title, mailBody, path, mailTo, reportName, loginUserId);
	}

	public Boolean sendEmails(String title, String mailBody, String path[], String mailTo, String[] reportName,
			String loginUserId) {
		try {
			MsgMail msgMail= msgMailService.sendEmails(loginUserId);
			if(msgMail!=null && !StringUtil.isEmptyString(msgMail.getId())){
				Map<String, String> fileMap=new HashMap<>();
				if(!path.equals("")){
					if (!StringUtils.isNotNullAndEmpty(reportName)) {
						reportName=null;
					}
					for (int i = 0; i < path.length; i++) {
						fileMap.put(path[i],reportName[i]); // 添加附件
					}
				}
				//编制加个性签名：
				mailBody=mailBody+msgMail.getContent();
				//判断发送内容中有没有内嵌的图片文件

				//索引mailBody中的图片路径
				List<String> pathList=msgMailService.htmlFilePath(mailBody);
				List<String> imagePathList=new ArrayList<>();
				if(CollectionUtils.isNotEmpty(pathList)){
					for(String imagePath:pathList){
						if(imagePath.indexOf(loginUserId) != -1 || imagePath.indexOf("999999999999999999999999999999") != -1){
							String getFilePath= LogicPathUtil.getFilePathByVirtualPath(StorageFileCacheManage.getSystemUseAddressId(),imagePath);
							mailBody=mailBody.replace(imagePath, getFilePath);
							imagePathList.add(getFilePath);
						}
					}
				}
				String[] imagePath=new String[imagePathList.size()];
				for(int i=0;i<imagePathList.size();i++){
					imagePath[i]=imagePathList.get(i);
				}
				EmailSubject mail =msgMailService.getMailClient(msgMail, mailTo, title, mailBody,fileMap,imagePath);
				mail.send();
				return true;
			}
		} catch ( AuthenticationFailedException e) {
			LoggerHelper.error(logger, e, "");
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return false;
		}

		return false;
	}

	public Boolean sendEmailWidthOrig(String title, String mailBody, String path, String mailTo, String reportName,
			String origReport, String origRpath, String loginUserId) {
		return msgMailService.sendEmailWidthOrig(title, mailBody, path, mailTo, reportName, origReport, origRpath,
				loginUserId);
	}

	/**
	 * 测试邮箱是否能发送邮件
	 * 
	 * @return
	 */
	public Boolean sendTestEmail(String sendMail, String STMP, String password) throws AuthenticationFailedException {
		return msgMailService.sendTestEmail(sendMail, STMP, password);
	}

	/**
	 * 保存用户邮件发送信息
	 * 
	 * @param mail
	 *            邮箱
	 * @param name
	 *            名字
	 * @param smtp
	 * @param password
	 * @return
	 */
	public Boolean saveUserMailInfo(String mail, String name, String smtp, String password, String content,
			String loginUserId) throws Exception {
		return msgMailService.saveUserMailInfo(mail, name, smtp, password, content, loginUserId);
	}

	public boolean deleteMailInfo(String name,String userId) throws Exception {
		return msgMailService.deleteMailInfo(name,userId);
	}

	/**
	 * 发送报告附件
	 * 
	 * @param title
	 * @param mailBody
	 * @param filePaths
	 * @param mailTo
	 * @param loginUserId
	 * @return
	 */
	public boolean sendEmailAttach(String title, String mailBody, Map<String, String> filePaths, String mailTo,
			String loginUserId) {
		MsgMail msg = msgMailService.sendEmailAttach(loginUserId);
		return sendEmailAttachs(title, mailBody, filePaths, mailTo, loginUserId,msg);
	}

	/**
	 * 添加一个常用的EMAIL
	 * 
	 * @param mail
	 *            email
	 * @return
	 */
	public Boolean addSendEMail(String mail, String loginUserId) throws Exception {
		return msgMailService.addSendEMail(mail, loginUserId);
	}

	/**
	 * 给企业发送激活码邮件
	 * 
	 * @param title
	 * @param mailBody
	 * @param mailTo
	 * @return
	 */
	public Boolean sendEnterpriseActivateCodeEmail(String title, String mailBody, String mailTo) {
		return msgMailService.sendEnterpriseActivateCodeEmail(title, mailBody, mailTo);
	}

	public String parseEmailHtml(MsgEmailSet msgMailSet, String title, String txt,String mailContent) {
		return msgMailService.parseEmailHtml(msgMailSet, title, txt,mailContent);
	}

	/**
	 * 保存邮件配置
	 * 
	 * @param string
	 * @param mail
	 * @param name
	 * @param smtp
	 * @param pw
	 * @return
	 */
	public boolean addMsgEmail(String string, String mail, String name, String smtp, String pw) {

		return msgMailService.addMsgEmail(string, mail, name, smtp, pw);
	}

	/**
	 * 获取msg_mail的单个信息
	 * 
	 */
	public MsgMail getMsgMailById(String id) throws Exception {

		return msgMailService.getMsgMailById(id);
	}

	/**
	 * 发送邮件： 邮件内容为HTML html内嵌文件 例如 <img src="" />
	 * 
	 * @param title
	 * @param mailBody
	 * @param path
	 * @param mailTo
	 * @param reportName
	 * @param htmlPath
	 * @return
	 * @throws Exception
	 */
	public boolean sendEmailHtmlFile(String title, String mailBody, String[] path, String mailTo, String[] reportName,
			String[] htmlPath, String loginUserId) throws Exception {
		return msgMailService.sendEmailHtmlFile(title, mailBody, path, mailTo, reportName, htmlPath, loginUserId);
	}

	/**
	 * 在FM中发送邮件
	 * 
	 * @param filesJson
	 *            要发送到文件
	 * @param mailTo
	 *            发给对象
	 * @param title
	 *            标题
	 * @param context
	 *            内容
	 * @return
	 */
	public String sendEMailInFM(String filesJson, String mailTo, String title, String context, MsgEmailSet msgMailSet,
			String loginUserId,List<VFileObject> vfs) {
		String mailContent ="";
		try {
			if (vfs == null || (vfs != null && vfs.size() == 0)) {
				return ResourceUtils.getMessage("MODULES_SENDING_NOT_SUCCESSFUL_NO_FILE_FOLDER");
			}

			MsgMail msg = msgMailService.sendEmailAttach(loginUserId);
			if(msg != null){
				mailContent = msg.getContent();
			}
			if(mailContent == null){
				mailContent = "";
			}
			
			Map<String, String> mapPaths = new HashMap<>();
			int iTotalSize = 0;
			int iSize = 0;
			if (vfs != null && vfs.size() > 0) {
				for (int i = 0; i < vfs.size(); i++) {
					try {
						VFileObject vf = vfs.get(i);
						iSize = (int) vf.getSize();
						iTotalSize = iTotalSize + iSize;
						mapPaths.put(vf.getFilePath(), vf.getFileRelactionName());
					} catch (Exception e) {
					}
				}
				iSize = iTotalSize;
			}
			if (iSize > CebaConfig.SEND_MAIL_MAX_SIZE) {
				return ResourceUtils.getMessage("MODULES_ANNEXES_REPORT_EXCEEDED")
						+ CebaConfig.SEND_MAIL_MAX_SIZE / 1024 / 1024 + "M";
			}

			String mailBody = msgMailService.parseEmailHtml(msgMailSet, title, context,mailContent);
			//String mailBody = context+"<br/>"+mailContent;
			String[] arr = mailTo.split(";");
			int times = 0;
			StringBuffer sendEmails = new StringBuffer();
			StringBuffer noneSendEmials = new StringBuffer();
			for (int i = 0; i < arr.length; i++) {
				if (!"".equals(arr[i])) {
					if (!sendEmailAttachs(title, mailBody, mapPaths, arr[i], loginUserId,msg)) {
						noneSendEmials.append(arr[i] + ";");
					} else {
						sendEmails.append(arr[i] + ";");
						msgMailService.addSendEMail(arr[i], loginUserId);
						times++;
					}
				}
			}
			if (times == arr.length) {
				return "0";
			} else if (times > 0 && times < arr.length) {
				return "[" + sendEmails + "]" + ResourceUtils.getMessage("PDFVER_SEND_SUCCESSFUL") + ",["
						+ noneSendEmials + "]" + ResourceUtils.getMessage("REPORT_SEND_FAILURE");
			} else {
				return ResourceUtils.getMessage("MODULES_SENDING_NOT_SUCCESSFUL_CHECK_MAILBOX_FILED_CORRECT");
			}

		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return ResourceUtils.getMessage("REPORT_SEND_FAILURE");
		}
/*
		return "0";*/
	}

	/**
	 * 根据ID取得邮件设置数据
	 * 
	 * @param id
	 * @return
	 */
	public MsgMail getMsgEmailByUserId(String id) {
		return msgMailService.getMsgEmailByUserId(id);
	}

	public boolean getMsgMailAddContent(String content) {
		return msgMailService.getMsgMailAddContent(content);
	}

	// MsgEmailValidLogService 类

	public MsgEmailSetService getMsgEmailSetService() {
		return msgEmailSetService;
	}

	public void setMsgEmailSetService(MsgEmailSetService msgEmailSetService) {
		this.msgEmailSetService = msgEmailSetService;
	}

	public MsgMailService getMsgMailService() {
		return msgMailService;
	}

	public void setMsgMailService(MsgMailService msgMailService) {
		this.msgMailService = msgMailService;
	}

	public MsgEmailValidLogService getMsgEmailValidLogService() {
		return msgEmailValidLogService;
	}

	public void setMsgEmailValidLogService(MsgEmailValidLogService msgEmailValidLogService) {
		this.msgEmailValidLogService = msgEmailValidLogService;
	}
	
	public UserInfoSet getUserInfoSet(IUser user){
		 return msgMailService.getUserInfoSet(user);
	 }


	/**
	 * 发送报告附件
	 * @param title
	 * @param mailBody
	 * @param filePaths
	 * @param mailTo
	 * @param loginUserId
	 * @return
	 */
	public boolean sendEmailAttachs(String title, String mailBody,
								   Map<String,String>filePaths, String mailTo,String loginUserId,MsgMail msgMail) {
		try {
			//索引mailBody中的图片路径
			List<String> pathList=msgMailService.htmlFilePath(mailBody);
			List<String> imagePathList=new ArrayList<>();
			if(CollectionUtils.isNotEmpty(pathList)){
				for(String imagePath:pathList){
					if(imagePath.indexOf(loginUserId) != -1 || imagePath.indexOf("999999999999999999999999999999") != -1){
//						String getFilePath=CebaPathUtil.getFilePathByVirtualPath(imagePath.replace(CebaPathUtil.getProjectContextPath(), ""));
						String getFilePath = LogicPathUtil.getBrowserPathToAbsolutelyPath(imagePath);
						mailBody=mailBody.replace(imagePath, getFilePath);
						imagePathList.add(getFilePath);
					}
				}
			}
			String[] imagePath=new String[imagePathList.size()];
			for(int i=0;i<imagePathList.size();i++){
				imagePath[i]=imagePathList.get(i);
			}

			if(msgMail !=null && !StringUtil.isEmptyString(msgMail.getId())){
				Map<String, String> fileMap=new HashMap<>();
				if(filePaths.size() > 0){
					String path = "";
					Iterator<String> it  = filePaths.keySet().iterator();
					while(it.hasNext()){
						path = it.next();
						if(FileHelper.exists(path)){
							fileMap.put(path,filePaths.get(path)); // 添加附件
						}
					}
				}

				EmailSubject mail = msgMailService.getMailClient(msgMail, mailTo, title, mailBody,fileMap,imagePath);
				mail.send();
				return true;
			}
		} catch ( AuthenticationFailedException e) {
			LoggerHelper.error(logger, e, "");
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return false;
	}

	public List<MsgMail> getAllMsgMail(){
		return msgMailService.getAllMsgMail();
	}

	public boolean updateContent(String id, String value) {
		return msgMailService.updateContent(id,value);
	}

}
